package com.pingan.haofang.searchcloud.index.rpc;

import com.pingan.haofang.searchcloud.common.redis.IncRedisQueue;
import com.pingan.haofang.searchcloud.common.redis.RedisQueueListener;
import com.pingan.haofang.searchcloud.common.redis.RedisQueueManager;
import com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 项目启动完成之后 在消费增量消息
 *
 * @author baojimin518
 * @version 1.0
 * @create 2018/12/20 17:02
 */
@Component
public class IndexIncMsgConsumer implements ApplicationListener<ContextRefreshedEvent> {

    Logger LOGGER = LoggerFactory.getLogger(IndexIncMsgConsumer.class);

    @Autowired
    private ThreadPoolExecutor incConsumerThreadCPool;

    @Autowired
    private RedisQueueListener redisQueueListener;

    @Resource(name = "redisQueueTemplate")
    private RedisTemplate redisTemplate;

    @Value("${indexBuild.incMsgConsumeRate:500}")
    private int rate;

    /**
     * 每次消息处理个数
     */
    @Value("${indexBuild.incMsgBatchSize:10}")
    private int batchSize = 10;

    /**
     * 每次消息处理个数
     */
    @Value("${indexBuild.incMsgMaxThreadQueueSize:0}")
    private int queueSize = 0;

    /**
     * 锁过期时间ms
     */
    @Value("${indexBuild.incMsgExpireTime:1000}")
    private int expireTime = 1000;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        LOGGER.info("inc msg watcher start!");
        incConsumerThreadCPool.execute(() -> {
            while (true) {
                if (incConsumerThreadCPool.getQueue().size() <= queueSize) {
                    Set<String> entries = redisTemplate.opsForHash().keys(IndexBuildConstants.INDEX_INC_KEY_HOLDER);
                    for (String key : entries) {
                        //队列有数据并且全量不阻塞
                        Boolean lock = redisTemplate.opsForHash().hasKey(IndexBuildConstants.LOCK, key.split(":")[1]);
                        //消息数量
                        Long keySize = redisTemplate.boundListOps(key).size();
                        if (keySize > 0 && !lock) {
                            IncRedisQueue incRedisQueue = RedisQueueManager.getInstanceOf(redisTemplate).buildMsgQueue(key, redisQueueListener)
                                    .setBatchSize(batchSize)
                                    .setExpireTime(expireTime);
                            incConsumerThreadCPool.submit(incRedisQueue);
                            LOGGER.info("inc task submited, inc-pool-info: core-{},pool-{},queue-{}", incConsumerThreadCPool.getCorePoolSize(),
                                    incConsumerThreadCPool.getPoolSize(), incConsumerThreadCPool.getQueue().size());
                        }
                        if (keySize > 0 && lock) {
                            LOGGER.info("inc msg locked, wait for full-build release the key:{}", key.split(":")[1]);
                        }
                    }
                }

                try {
                    Thread.sleep(rate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
